package dou.net.socket;

import java.io.IOException;
import java.util.concurrent.BlockingDeque;

/**
 * 为客户端套接字接收数据提供独立运行的一个线程
 * @author wizardc
 */
public class ReadThread extends Thread
{
    //记录有读取请求的套接字对象列表
    private BlockingDeque<IClientSocket> _queue;

    /**
     * 构造函数
     * @param serverName 该线程的名称
     * @param queue 记录有读取请求的套接字对象列表
     */
    public ReadThread(String serverName, BlockingDeque<IClientSocket> queue)
    {
        super("ReadThread-" + serverName);
        _queue = queue;
    }

    @Override
    public void run()
    {
        while(true)
        {
            try
            {
                IClientSocket socket = _queue.take();
                try
                {
                    if(socket.readBuffer() == -1)
                    {
                        closeSocket(socket);
                    }
                }
                catch(IOException exception)
                {
                    closeSocket(socket);
                }
            }
            catch(Exception exception)
            {
            }
        }
    }

    /**
     * 关闭一个套接字对象
     * @param socket 要被关闭的套接字对象
     */
    private void closeSocket(IClientSocket socket)
    {
        try
        {
            socket.close();
        }
        catch(IOException exception)
        {
        }
    }
}
